#!/usr/bin/env python
"""

    cache_genes_from_gtf.py
    [--log_file PATH]
    [--verbose]

"""

################################################################################
#
#   cache_genes_from_gtf
#
#
#   Copyright (c) 3/11/2010 Leo Goodstadt, Andreas Heger
#   
#   Permission is hereby granted, free of charge, to any person obtaining a copy
#   of this software and associated documentation files (the "Software"), to deal
#   in the Software without restriction, including without limitation the rights
#   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#   copies of the Software, and to permit persons to whom the Software is
#   furnished to do so, subject to the following conditions:
#   
#   The above copyright notice and this permission notice shall be included in
#   all copies or substantial portions of the Software.
#   
#   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#   THE SOFTWARE.
#################################################################################

import sys, os
import os.path


# add self to search path for testing
if __name__ == '__main__':
    exe_path = os.path.split(os.path.abspath(sys.argv[0]))[0]
    # Use import path from <<../python_modules>>
    sys.path.append(os.path.abspath(os.path.join(exe_path,"..", "python_modules")))
    module_name = os.path.split(sys.argv[0])[1]
    module_name = os.path.splitext(module_name)[0];
else:
    module_name = __name__



#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   options        


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888


if __name__ == '__main__':
    from optparse import OptionParser
    import StringIO
    
    parser = OptionParser(version="%prog 1.0", usage = "\n\n    %progs [options]")
    parser.add_option("-r", "--search_path_root", dest="search_path_root",
                      metavar="FILE", 
                      type="string",
                      help="Name and path of input file. "
                          "Defaults to reading from STDIN.")
    parser.add_option("-i", "--index_file", dest="index_file",
                      metavar="FILE", 
                      type="string",
                      help="Name and path of index file. "
                          "Index from release/species to gtf file name.")
    parser.add_option("--ignore_cache", dest="ignore_cache",
                        action="store_true", default=False,
                        help="Re-cache genes from GTF.")
    
    #
    #   general options: verbosity / logging
    # 
    parser.add_option("-v", "--verbose", dest = "verbose",
                      action="count", default=0,
                      help="Print more verbose messages for each additional verbose level.")
    parser.add_option("-L", "--log_file", dest="log_file",
                      metavar="FILE", 
                      type="string",
                      help="Name and path of log file")
    parser.add_option("--skip_parameter_logging", dest="skip_parameter_logging",
                        action="store_true", default=False,
                        help="Do not print program parameters to log.")
    parser.add_option("--debug", dest="debug",
                        action="count", default=0,
                        help="Set default program parameters in debugging mode.")
    
    
    
    
    # get help string
    f =StringIO.StringIO()
    parser.print_help(f)
    helpstr = f.getvalue()
    (options, remaining_args) = parser.parse_args()
    
        options.log_file = os.path.splitext(options.index_file)[0] + ".log"
        if options.log_file == options.index_file:
            index_file_path = os.path.split(os.path.abspath(options.index_file))[0]
            options.log_file = os.path.join(index_file_path, "cache_genes_from_gtf.log")
            if options.log_file == options.index_file:
                options.log_file = None
    
    # 
    #   mandatory options
    # 
    from options import check_mandatory_options
    mandatory_options = ["log_file", "index_file", "search_path_root"]
    check_mandatory_options (options, mandatory_options, helpstr)
    
    
#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   imports        


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888


#from json import dumps
#from collections import defaultdict



#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Functions        


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Logger


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

if __name__ == '__main__':
    #
    #   set up log
    # 
    import logging
    logger = logging.getLogger(module_name)
    from lg_program_logging import  setup_std_logging, MESSAGE
    setup_std_logging(logger, options.log_file, options.verbose)
    

    #
    #   log programme parameters
    # 
    if not options.skip_parameter_logging:
        programme_name = os.path.split(sys.argv[0])[1]
        from options import get_option_strings
        logger.info("%s %s" % (programme_name, " ".join(get_option_strings(parser, options))))

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Functions


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Main logic


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
if __name__ == '__main__':
    

    index_file = open(options.index_file,  "w")
    for root, dirs, files in os.walk(options.search_path_root):
        for gtf_file in files:
            parts = gtf_file.split(".")
            if len(parts) < 3:
                continue
            if parts[-1] == "gz":
                parts.pop()
            if len(parts) < 3:
                continue
            if parts[-1] != "gtf":
                continue
            species_name = parts[0].replace("_", " ").lower()
            release = parts[-2]
            gtf_path = os.path.join(root, gtf_file)
            index_file.write("%s\t%s\t%s\n" % 
                                (species_name, release, gtf_path))
            
            gene_structures = gene.t_parse_gtf(species_name)
            logger.debug("Caching %s" % gtf_path)
            genes_by_type = gene_structures.get_genes(gtf_path, logger, ignore_cache = options.ignore_cache)

